import React, { useState, useEffect, useRef } from "react";
import { Spin, Upload, Button, Icon, message } from "antd";
import "codemirror/lib/codemirror.css";
import "@toast-ui/editor/dist/toastui-editor.css";

import style from "./index.module.scss";
import { FileApi } from "@/api/file";

interface IProps {
  value: string;
  onChange: (html) => void;
}
let BraftEditor;
export const Editor: React.FC<IProps> = ({ value = "", onChange }) => {
  const editorRef = useRef(null);
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    if (mounted) {
      editorRef.current.editorInst.setHtml(value);
    }
  }, [value, mounted]);
  useEffect(() => {
    Promise.all([import("@toast-ui/react-editor")]).then(([res]) => {
      BraftEditor = res.Editor;
      setMounted(true);
    });
    return () => {
      setMounted(false);
    };
  }, []);
  // 文件上传方法
  const upload = async file => {
    const { size, type, name } = file;
    if (size < 1024 * 1024 * 0.01) {
      return new Promise(resolve => {
        const reader = new FileReader();
        reader.onload = function() {
          resolve(this.result);
        };
        reader.readAsDataURL(file);
      });
    } else {
      let ld = message.loading("文件上传中");
      return FileApi.upload(file)
        .then(res => {
          ld();
          return res.url;
        })
        .catch(() => {
          ld();
          message.error("文件上传失败，可能过大！");
        });
    }
  };
  const save = () => {

  }
  const preview = () => {

  }
  const fileSelect = () => {
    
  }
  return mounted ? (
    <div className={style.wrapper}>
      <BraftEditor
        ref={editorRef}
        previewStyle="vertical"
        height="800px"
        initialEditType="markdown"
        useCommandShortcut={true}
        language={"zh"}
        placeholder="请输入文章内容"
        onChange={() => {
          const html = editorRef.current.editorInst.getHtml();
          onChange(html);
        }}
        hooks={{
          addImageBlobHook: function(file, callback) {
            upload(file).then(url => {
              callback(url, file.name);
            });
          }
        }}
      />
    </div>
  ) : (
    <Spin tip="编辑器加载中" spinning={true}></Spin>
  );
};
